//
//  MJRefreshHeaderView.m
//  weibo
//
//  Created by mj on 13-2-26.
//  Copyright (c) 2013年 itcast. All rights reserved.
//  下拉刷新

#define kPullToRefresh @""
#define kReleaseToRefresh @"释放更新"
#define kRefreshing @"加载中..."

#define kTimeKey @"MJRefreshHeaderView"

#import "MJRefreshHeaderView.h"

@interface MJRefreshHeaderView()<UIScrollViewDelegate>
{
//    UIScrollView *headerScrollview;
}
// 最后的更新时间
@property (nonatomic, strong) NSDate *lastUpdateTime;
@property (strong, nonatomic) UIImageView *logoAnimationImage;
@property (strong, nonatomic) UIImageView *textAnimationImage;
@end

@implementation MJRefreshHeaderView

+ (id)header
{
    return [[MJRefreshHeaderView alloc] init];
}

#pragma mark - UIScrollView相关
#pragma mark 重写设置ScrollView
- (void)setScrollView:(UIScrollView *)scrollView
{
    [super setScrollView:scrollView];
    
    [_scrollView removeObserver:self forKeyPath:@"contentOffset" context:nil];
    // 设置scrollView
    _scrollView = scrollView;
    
    [_scrollView addSubview:self];
    // 监听contentOffset
    [_scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];

    // 设置边框
    self.frame = CGRectMake(0, -kViewHeight, scrollView.frame.size.width, kViewHeight);
    self.logoAnimationImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"refreshBackground_logo"]];
//    _logoAnimationImage.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 2 - 80, 50, 30, 30);
    _logoAnimationImage.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 2 - 70 - 49 * 0.2, 50, 20 + 49*0.2, 20 + 49*0.20);
    [self addSubview:_logoAnimationImage];
    self.textAnimationImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"refreshBackground_text"]];
//    _textAnimationImage.frame = CGRectMake(_logoAnimationImage.frame.size.width + _logoAnimationImage.frame.origin.x + 10, 50, 120, 30);
    _textAnimationImage.frame = CGRectMake(_logoAnimationImage.frame.size.width + _logoAnimationImage.frame.origin.x + 10, 50, 100 + 49 * 0.3, 20 + 49 * 0.2);
    [self addSubview:_textAnimationImage];
    // 加载时间
    _lastUpdateTime = [[NSUserDefaults standardUserDefaults] objectForKey:kTimeKey];
    _arrowImage.hidden = YES;
    _activityView.hidden = YES;
    _statusLabel.hidden = YES;
    _activityView = nil;
    _arrowImage = nil;
    _statusLabel = nil;
    // 设置时间
    [self updateTimeLabel];
}

#pragma mark - 状态相关
#pragma mark 设置最后的更新时间
- (void)setLastUpdateTime:(NSDate *)lastUpdateTime
{
    _lastUpdateTime = lastUpdateTime;
    
    // 归档
    [[NSUserDefaults standardUserDefaults] setObject:_lastUpdateTime forKey:kTimeKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // 更新时间
    [self updateTimeLabel];
}

#pragma mark 更新时间字符串
- (void)updateTimeLabel
{
    if (!_lastUpdateTime) return;
    
    // 1.获得年月日
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit;
    NSDateComponents *cmp1 = [calendar components:unitFlags fromDate:_lastUpdateTime];
    NSDateComponents *cmp2 = [calendar components:unitFlags fromDate:[NSDate date]];
    
    // 2.格式化日期
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if ([cmp1 day] == [cmp2 day]) { // 今天
        formatter.dateFormat = @"今天 HH:mm";
    } else if ([cmp1 year] == [cmp2 year]) { // 今年
        formatter.dateFormat = @"MM-dd HH:mm";
    } else {
        formatter.dateFormat = @"yyyy-MM-dd HH:mm";
    }
//    NSString *time = [formatter stringFromDate:_lastUpdateTime];
    
    // 3.显示日期
    _lastUpdateTimeLabel.text = [NSString stringWithFormat:@""];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    float offset = fabs(_scrollView.contentOffset.y);
    if (offset > 47) {
        if (offset < 90) {
            _logoAnimationImage.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 2 - 70 - offset * 0.2, 50, 20 + offset*0.2, 20 + offset*0.20);
            _textAnimationImage.frame = CGRectMake(_logoAnimationImage.frame.size.width + _logoAnimationImage.frame.origin.x + 10, 50, 100 + offset * 0.3, 20 + offset * 0.2);
        }
    } else {
        _logoAnimationImage.frame = CGRectMake([UIScreen mainScreen].bounds.size.width / 2 - 70 - 49 * 0.2, 50, 20 + 49*0.2, 20 + 49*0.20);
        _textAnimationImage.frame = CGRectMake(_logoAnimationImage.frame.size.width + _logoAnimationImage.frame.origin.x + 10, 50, 100 + 49 * 0.3, 20 + 49 * 0.2);
    }
    if ([@"contentOffset" isEqualToString:keyPath]) {
        CGFloat offsetY = _scrollView.contentOffset.y * self.viewType;
        CGFloat validY = self.validY;
        if (!self.userInteractionEnabled || self.alpha <= 0.01 || self.hidden
            || _state == RefreshStateRefreshing
            || offsetY <= validY) return;
        
        // 即将刷新 && 手松开
        if (_scrollView.isDragging) {
            CGFloat validOffsetY = validY + kViewHeight;
            if (_state == RefreshStatePulling && offsetY <= validOffsetY) {
                // 转为普通状态
#ifdef NeedAudio
                AudioServicesPlaySystemSound(_normalId);
#endif
                [self setState:RefreshStateNormal];
            } else if (_state == RefreshStateNormal && offsetY > validOffsetY) {
                // 转为即将刷新状态
#ifdef NeedAudio
                AudioServicesPlaySystemSound(_pullId);
#endif
                [self setState:RefreshStatePulling];
            }
        } else {
            if (_state == RefreshStatePulling) {
                // 开始刷新
#ifdef NeedAudio
                AudioServicesPlaySystemSound(_refreshingId);
#endif
                [self setState:RefreshStateRefreshing];
            }
        }
    }

}
#pragma mark 设置状态
- (void)setState:(RefreshState)state
{
    if (_state == state) return;
    
    [super setState:state];
    
    // 保存旧状态
    RefreshState oldState = _state;
    
	switch (_state = state) {
		case RefreshStatePulling:
        {
//            _statusLabel.text = kReleaseToRefresh;
            [UIView animateWithDuration:0.2 animations:^{
//                _arrowImage.transform = CGAffineTransformMakeRotation(M_PI);
                
                UIEdgeInsets inset = _scrollView.contentInset;
                inset.top = 0;
                _scrollView.contentInset = inset;
            }];
			break;
        }
            
		case RefreshStateNormal:
        {
//			_statusLabel.text = kPullToRefresh;
            [self endAnimation];
            // 刷新完毕
            if (oldState == RefreshStateRefreshing) {
                // 保存刷新时间
                self.lastUpdateTime = [NSDate date];
#ifdef NeedAudio
                AudioServicesPlaySystemSound(_endRefreshId);
#endif     
            }
            [UIView animateWithDuration:0.2 animations:^{
//                _arrowImage.transform = CGAffineTransformIdentity;
                UIEdgeInsets inset = _scrollView.contentInset;
                inset.top = 0;
                _scrollView.contentInset = inset;
            }];
			break;
        }
            
		case RefreshStateRefreshing:
        {
            _statusLabel.text = kRefreshing;
            [self beginAnimation];
            [UIView animateWithDuration:0.2 animations:^{
                // 1.顶部多出65的滚动范围
                UIEdgeInsets inset = _scrollView.contentInset;
                inset.top = kViewHeight;
                _scrollView.contentInset = inset;
                // 2.设置滚动位置
                _scrollView.contentOffset = CGPointMake(0, -kViewHeight);
            }];
			break;
        }
	}
}
- (void)beginAnimation
{
//    CABasicAnimation *animation = [CABasicAnimationWithKeyPath:@"transform.scale"];
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation.fromValue = [NSNumber numberWithFloat:0.7f];
    animation.toValue = [NSNumber numberWithFloat:1.0f];
    animation.autoreverses = YES;
    animation.repeatCount = MAXFLOAT;
    animation.duration = 0.6;//不设置时候的话，有一个默认的缩放时间.
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    [_logoAnimationImage.layer addAnimation:animation forKey:nil];
}
- (void)endAnimation
{
    [_logoAnimationImage.layer removeAllAnimations];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSLog(@"%f", scrollView.contentOffset.y);
}
#pragma mark - 在父类中用得上
// 合理的Y值
- (CGFloat)validY
{
    return 0;
}
// view的类型
- (int)viewType
{
    return RefreshViewTypeHeader;
}
@end